package com.itcast.yygh.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itcast.common.exception.YyghException;
import com.itcast.common.utils.JwtHelper;
import com.itcast.yygh.model.enums.AuthStatusEnum;
import com.itcast.yygh.model.model.user.Patient;
import com.itcast.yygh.model.model.user.UserInfo;
import com.itcast.yygh.model.vo.user.LoginVo;
import com.itcast.yygh.model.vo.user.UserAuthVo;
import com.itcast.yygh.model.vo.user.UserInfoQueryVo;
import com.itcast.yygh.user.mapper.UserInfoMapper;
import com.itcast.yygh.user.service.PatientApiService;
import com.itcast.yygh.user.service.UserInfoService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {
    //引入redis的依赖
    @Resource
    private RedisTemplate<String,String> redisTemplate;

    @Resource
    private PatientApiService patientApiService;

    @Override
    public Map<String, Object> login(LoginVo loginVo) {
        //1.先校验手机号和验证码
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();
        if(StringUtils.isEmpty(phone)||StringUtils.isEmpty(code)){
            throw new YyghException(20001,"手机号或验证码不能为空!");
        }
        //todo 校验redis中的验证码是否跟用户的一致
        String redisCode = redisTemplate.opsForValue().get(phone);
        if(!redisCode.equals(code)){
            throw new YyghException(20001,"验证码不一致!");
        }
        //2.根据手机号查询对应的用户信息
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone",phone);

        //根据手机号查询用户对象
        UserInfo userInfo = baseMapper.selectOne(queryWrapper);
        //3.如果没有查到用户需要先保存手机号信息
        if(Objects.isNull(userInfo)){
            //保存当前用户的信息
            UserInfo userInfo1 = new UserInfo();
            userInfo1.setName("");
            userInfo1.setPhone(phone);
            userInfo1.setStatus(1);
            baseMapper.insert(userInfo1);
        }
        //4.如果查询用户信息校验用户的禁用状态
        userInfo = baseMapper.selectOne(queryWrapper);
        if(userInfo.getStatus()!=1){
            throw new YyghException(20001,"用户处于禁用状态!");
        }
        //5.返回页面中需要的数据用户名和token
        Map<String,Object> map = new HashMap<>();
        String name = userInfo.getName();
        if(StringUtils.isEmpty(name)){
            name = userInfo.getNickName();
        }
        if(StringUtils.isEmpty(name)){
            name = userInfo.getPhone();
        }
        //用户名
        map.put("name",name);
        //生成token码
        String token = JwtHelper.createToken(userInfo.getId(), name);

        map.put("token",token);
        return map;
    }

    @Override
    public void userAuth(Long userId, UserAuthVo userAuthVo) {
        //根据用户id查询用户信息
        UserInfo userInfo = baseMapper.selectById(userId);
        //设置认证信息
        //认证人姓名
        userInfo.setName(userAuthVo.getName());
        //其他认证信息
        userInfo.setCertificatesType(userAuthVo.getCertificatesType());
        userInfo.setCertificatesNo(userAuthVo.getCertificatesNo());
        userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());
        userInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus());
        //进行信息更新
        baseMapper.updateById(userInfo);
    }

    @Override
    public IPage<UserInfo> findPage(Page<UserInfo> pages, UserInfoQueryVo userInfoQueryVo) {
        //1.获取分页查询的条件
        //关键字
        String keyword = userInfoQueryVo.getKeyword();
        //状态
        Integer status = userInfoQueryVo.getStatus();
        //认证状态
        Integer authStatus = userInfoQueryVo.getAuthStatus();
        //创建开始时间
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin();
        //创建结束时间
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd();
        //2.拼接查询条件
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(keyword)){
            queryWrapper.like("name",keyword);
        }
        if(!StringUtils.isEmpty(status)){
            queryWrapper.eq("status",status);
        }
        if(!StringUtils.isEmpty(authStatus)){
            queryWrapper.eq("auth_status",authStatus);
        }
        if(!StringUtils.isEmpty(createTimeBegin)){
            queryWrapper.ge("create_time",createTimeBegin);
        }
        if(!StringUtils.isEmpty(createTimeEnd)){
            queryWrapper.le("create_time",createTimeEnd);
        }
        //3.进行分页的数据查询
        IPage<UserInfo> userInfoPage = baseMapper.selectPage(pages, queryWrapper);
        //4.需要设置其他属性的内容
        userInfoPage.getRecords().stream().forEach(item->{
            //封装其他属性
            this.packageUserInfo(item);
        });
        return userInfoPage;
    }

    //编号变成对应值封装
    private UserInfo packageUserInfo(UserInfo userInfo) {
        //处理认证状态编码
        userInfo.getParam().put("authStatusString",AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));
        //处理用户状态 0  1
        String statusString = userInfo.getStatus().intValue()==0 ?"锁定" : "正常";
        userInfo.getParam().put("statusString",statusString);
        return userInfo;
    }

    @Override
    public void lock(Long userId, int status) {
        //1.先判断当前状态是否有值
        if(status == 0 || status == 1){
            //2.修改用户的锁定状态
            UserInfo userInfo = this.getById(userId);
            userInfo.setStatus(status);
            baseMapper.updateById(userInfo);
        }

    }

    @Override
    public Map<String, Object> show(Long id) {
        Map<String,Object> map = new HashMap<>();
        //1.根据用户id查询用户的信息数据
        UserInfo userInfo = this.packageUserInfo(baseMapper.selectById(id));
        //2.根据id查询就诊人列表数据
        List<Patient> patients = patientApiService.findAllByUserId(id);
        //3.将两个对象封装到map集合中
        map.put("userInfo",userInfo);
        map.put("patientList",patients);
        return map;
    }

    @Override
    public void approval(Long id, int authStatus) {
        if(authStatus ==2 || authStatus == -1){
            UserInfo userInfo = baseMapper.selectById(id);
            userInfo.setAuthStatus(authStatus);
            baseMapper.updateById(userInfo);
        }
    }
}
